package zh.dummy.netty;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import zh.dummy.netty.client.handler.DefaultClientChannelHandler;

public class NettyClient {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private final String defaultHost = "127.0.0.1";
	private final int defaultPort = 9100;
	private String host;
	private volatile Channel channel;
	private volatile static NettyClient nettyClient;
	public volatile static boolean runEnable = true;
	private int port;
	
	private ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
	
	private EventLoopGroup group = new NioEventLoopGroup();
	
	private NettyClient(){
	}
	
	public static NettyClient getInstance(){
		if(nettyClient == null){
			synchronized (NettyClient.class) {
				nettyClient = new NettyClient();
			}
		}
		return nettyClient;
	}
	
	public void bind(String host,int port){
		this.host = host;
		this.port = port;
	}
	
	public void bind(String host){
		this.host = host;
	}
	
	public void bind(int port){
		this.port = port;
	}
	private void doConnect(){
		ensureInet();
		try{
			ChannelHandler handler = new DefaultClientChannelHandler();
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class)
				.option(ChannelOption.TCP_NODELAY, true)
				.handler(handler);
			ChannelFuture future = b.connect(host,port).sync();
			if(logger.isInfoEnabled()){
				logger.info("connected to host:{},port:{}",new Object[]{host,port});
			}
			channel = future.channel();
			channel.closeFuture().sync();
		} catch (Exception e) {
			if(logger.isInfoEnabled()){
				logger.info("disconnected to /{}:{} error:{}",new Object[]{host,port,e.getMessage()});
			}
		} finally{
			if(runEnable){
				reconnect();
			}else{
				executor.shutdown();
			}
		}
	}
	private void reconnect() {
		executor.execute(new Runnable(){
			public void run(){
				try{
					TimeUnit.SECONDS.sleep(5);
					try{
						if(logger.isInfoEnabled()){
							logger.info("reconnect to /{}:{}",new Object[]{host,port});
						}
						doConnect();
					} catch(Exception e) {
						e.printStackTrace();
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
	}

	private void ensureInet() {
		if(host == null){
			host = this.defaultHost;
		}
		if(port == 0){
			port = this.defaultPort;
		}
	}

	public void connect() {
		executor.execute(new Runnable(){
			@Override
			public void run() {
				doConnect();
			}
		});
	}

	public Channel getChannel(){
		return channel;
	}

}